package com.znufe.exam.service.impl;

import com.znufe.exam.base.RestResponse;
import com.znufe.exam.service.IWxAuthService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: Gongjc
 * @Date: 2020/11/14
 * @Version 1.0
 */
@Service
public class WxAuthService implements IWxAuthService {

    @Autowired
    private WxMpService srvMpService;

    @Override
    public Object getSrvOpenid(String code) throws WxErrorException {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = getSrvAccessToken(code);
        String openId = wxMpOAuth2AccessToken.getOpenId();
        return RestResponse.ok(openId);
    }

    private WxMpOAuth2AccessToken getSrvAccessToken(String code) throws WxErrorException {
        return srvMpService.oauth2getAccessToken(code);
    }

    @Override
    public Object getSrvUser(String code) throws WxErrorException {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = srvMpService.oauth2getAccessToken(code);
        WxMpUser wxMpUser = srvMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        return RestResponse.ok(wxMpUser);
    }
}
